<template>
  <div id="app">
	<div class="title"><a class="backPage iconfont icon-icon-test" @click="$router.back(-1)"></a>商品详情</div>
	<el-form class="form" label-position="top" v-loading="loading">
		<el-form-item label="商品标题">
			<el-input v-model.trim="detail.product_name"></el-input>
		</el-form-item>
		<el-form-item label="商品图片">
			<el-upload 
				:show-file-list="false" 
				:action="baseUrl + '/api/console/system/upload'"
				:headers="{authorizedkey:authorized_key}"
				:on-success="productImgUpload"
				:data="{
					bid: createBid()
				}"
				class="elupload">
				<div v-if="!detail.product_picture.length" class="addImg"><i class="el-icon-plus"></i></div>
				<img v-else :src="detail.product_picture[0].url" class="head" />
			</el-upload>
		</el-form-item>
		<el-form-item label="商品介绍">
			<div class="detail-imgs">
				<div class="dimg" :key="img.id+index" v-for="(img, index) in detail.pro_detail_picture">
					<img :src="img.url" alt="">
					<i @click="delDetailImg(img.id)" class="close el-icon-circle-close" title="删除"></i>
				</div>
				<el-upload 
					:show-file-list="false" 
					:action="baseUrl + '/api/console/system/upload'"
					:headers="{authorizedkey:authorized_key}"
					:on-success="productDetailImgsUpload"
					:data="{
						bid: createBid()
					}"
					title="添加图片"
					class="elupload">
					<div class="addImg"><i class="el-icon-plus"></i></div>
				</el-upload>
			</div>
		</el-form-item>
		<el-row :gutter="60">
			<el-col :span="12">
				<div class="grid-content bg-purple">
					<el-form-item label="发货时长">
						<el-input v-model.trim="detail.send_time"></el-input>
					</el-form-item>
				</div>
			</el-col>
			<el-col :span="12">
				<div class="grid-content bg-purple">
					<el-form-item label="售价（单位：积分）">
						<el-input v-model.trim.number="detail.price"></el-input>
					</el-form-item>
				</div>
			</el-col>
			<el-col :span="12">
				<div class="grid-content bg-purple">
					<el-form-item label="库存个数">
						<el-input v-model.trim.number="detail.count"></el-input>
					</el-form-item>
				</div>
			</el-col>
			<el-col :span="12">
				<div class="grid-content bg-purple">
					<el-form-item label="单个用户可兑换次数（0为不限制）">
						<el-input v-model.trim.number="detail.pro_limit"></el-input>
					</el-form-item>
				</div>
			</el-col>
			<el-col :span="12">
				<div class="grid-content bg-purple">
					<el-form-item label="类型">
						<el-select v-model.number="detail.protype" placeholder="请选择" style="width:100%;">
							<el-option label="实物" :value="1"></el-option>
							<el-option label="虚拟" :value="0"></el-option>
						</el-select>
					</el-form-item>
				</div>
			</el-col>
			<el-col :span="24">
				<div class="grid-content bg-purple">
					<el-form-item label="所需资料">
						<el-row :gutter="60">
							<el-col :span="12" v-for="(item,index) in userCollects" :key="index">
								<div class="need_info clearfix">
									<div class="user-collect-box">
										<el-input v-model.trim="item.name"></el-input>
										<div class="delBtn" @click="delUserCollect(item.id)">删除</div>
									</div>
								</div>
							</el-col>
						</el-row>
						<div class="add" @click="addUserCollect">添加</div>
					</el-form-item>
				</div>
			</el-col>
		</el-row>
		<el-button @click="onSubmit" type="primary" style="margin-top:15px;">立即保存</el-button>
	</el-form>
  </div>
</template>
<script>
import utils from '@/utils/index';
import env from '@/config/env';
import deepClone from '@/utils/deepClone';
import fetch from '@/api/axios';
export default {
	data() {
		return {
			authorized_key:  utils.handleLocalStorage.get('authorized_key'),
			baseUrl: env.baseUrl,
			bid: '',
			loading: false,

			collectId: 1,

			action: 0,   // 0: add,   1: update
			id: 0,
			detail: {
				need_user_info: [],
				product_name: '',
				product_picture: [],
				pro_detail_picture: [],
				pro_describe: '',
				send_time: '',
				price: 0,
				pro_limit: 0,
				protype: 0,
				count: 0,
			},
			userCollects: [],
		}
	},
	created(){
		let id = this.$route.query.id;
		this.id = id;
		if(id){
			this.action = 1;
			this.getDetail();
		}else{
			this.action = 0;
		}


	},
	methods: {
		makeCollectData(detail){
			let userCollects = detail.need_user_info;
			this.userCollects = userCollects.map((v, k)=>{
				let id = k+1;
				return {id: id, name: v.name}
			});
			this.collectId = userCollects.length + 1;
		},
		getDetail(){
			this.loading = true;
			fetch.get('/api/console/user/score/product', {
				pro_id: this.id
			}).then(res=>{
				let data = res.data;
				if(data.code == 0){
					this.detail = data.data;
					this.makeCollectData(this.detail);
				}else{
					this.$message.error(data.message);
				}
			}).catch(err=>{
				this.$message.error('网络连接失败，请稍后重试');
			}).finally(()=>{
				this.loading = false;
			});
		},
		addUserCollect(){
			this.userCollects.push({id:this.collectId++, name: '', value: ''});
		},
		delUserCollect(id){
			let infos = this.userCollects.filter(v=>v.id != id);
			this.userCollects = [...infos];
		},
		createBid() {
            let prefix = utils.createUploadPrefix('Task');
            let bid = prefix + '-' +  utils.createBidFn();
            this.bid = bid;
            return  bid;
        },
		productImgUpload(res){
			let img = res.data.url;
			let id = res.data.id;
			this.$set(this.detail, 'product_picture', [{
				url: img,
				id: id
			}]);
		},
		productDetailImgsUpload(res){
			let img = res.data.url;
			let id = res.data.id;
			let pro_detail_picture = this.detail.pro_detail_picture || [];
			pro_detail_picture.push({
				url: img,
				id: id
			});
			this.$set(this.detail, 'pro_detail_picture', [...pro_detail_picture]);
		},
		delDetailImg(id){
			let detailImgs = this.detail.pro_detail_picture;
			let newImgs = detailImgs.filter(v=>{
				return v.id != id
			});
			this.detail.pro_detail_picture = [...newImgs];
		},
		validate(){
			let detail = this.detail;
			let status = true;
			if(detail.product_name === ''){
				status = false;
			}
			if(detail.product_picture.length == 0){
				status = false;
			}
			if(detail.pro_detail_picture.length == 0){
				status = false;
			}
			if(detail.send_time === ''){
				status = false;
			}
			if(detail.count === ''){
				status = false;
			}
			if(detail.price === ''){
				status = false;
			}
			if(detail.pro_limit === ''){
				status = false;
			}
			if(!status){
				this.$message.error('请完善表单信息');
			}
			return status;
		},
		getFormData(){
			let detail = deepClone(this.detail);
			let {product_picture, pro_detail_picture} = detail;
			let productPictures = product_picture.map(v=>v.id);
			let productDetailPictures = pro_detail_picture.map(v=>v.id);
			detail.product_picture = JSON.stringify(productPictures);
			detail.pro_detail_picture = JSON.stringify(productDetailPictures);
			let userCollects = this.userCollects.filter(v=>v.name!=='');
			detail.need_user_info = JSON.stringify(userCollects.map(v=>{
				return {
					name: v.name,
					value: v.value
				}
			}));
			return detail;
		},
		onSubmit(){
			let status = this.validate();
			if(!status){
				return false;
			}
			let formData = this.getFormData();
			if(this.action){
				this.update(formData);
			}else{
				this.add(formData);
			}
		},
		add(formData){
			let _this = this;
			
			this.loading = true;
			fetch.post('/api/console/user/score/product', {
				product: {...formData}
			}).then(res=>{
				let data = res.data;
				if(data.code == 0){
					_this.$message.success('商品添加成功');
					_this.$router.push('/increment/integral/goods');
				}else{
					_this.$message.error(data.message);
				}
			}).catch(err=>{
				_this.$message.error(err);
			}).finally(()=>{
				_this.loading = false;
			});
		},
		update(formData){
			let _this = this;
			this.loading = true;
			fetch.put('/api/console/user/score/product', {
				product: {...formData}
			}).then(res=>{
				let data = res.data;
				if(data.code == 0){
					_this.$message.success('提交成功');
					_this.$router.push('/increment/integral/goods');
				}else{
					_this.$message.error(data.message);
				}
			}).catch(err=>{
				_this.$message.error(err);
			}).finally(()=>{
				_this.loading = false;
			});
		}
	},
	mounted() {

	}
}
</script>
<style lang="scss" scoped>
	.form{
		width:620px;
	}
	.elupload{
		.head{
			width:150px;
			height:150px;
			border: 1px solid #eee;
		}
		.addImg{
			width: 150px;
			height: 150px;
			font-size: 45px;
			line-height: 150px;
			background: #F9F9F9;
			color: #eaeaea;
			border: 1px dashed #eee;
		}
	}
	.editor {
		width: 100%;
		height: 270px;
		overflow: hidden;
		.w-e-text-container{
			height:200px;
		}
	}
	.add{
		cursor: pointer;
		color:#9a9a9a;
	}
	.need_info{
		// &>div{
		// 	float:left;
		// 	margin-right:25px;
		// 	width:calc((100% - 50px) / 3);
		// 	margin-bottom:20px;
		// 	&:nth-child(3n){
		// 		margin-right:0;
		// 	}
		// }
		.user-collect-box{
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100%;
			margin-bottom: 20px;
			.delBtn{
				color: #b0b0b0;
				width:40px;
				margin-left: 18px;
				cursor: pointer;
			}
		}
	}
	.detail-imgs{
		display: flex;
		flex-wrap: nowrap;
		flex: 1;
		justify-content: flex-start;
		align-items: flex-start;
	}
	.detail-imgs .dimg{
		width: 150px;
		height: 150px;
		position: relative;
		border: 1px solid #eee;
		margin: 0 20px 20px 0;
		text-align: center;
		line-height: 150px;
		display: flex;
		justify-content: center;
		align-items: center;
		img{
			width: 150px;
			height: 150px;
		}
		i.close{
			width: 20px;
			height: 20px;
			position: absolute;
			top:-8px;
			right: -8px;
			font-size: 20px;
			color: #999;
			cursor: pointer;
			border-radius: 50%;
			background: #FFF;
		}
		i.add{
			font-size: 100px;
			color: #999;
		}
	}
</style>